<template>
  <div>
    <header style="display: flex; margin-bottom: -0.5%">
      <h1>仿真验证</h1>
    </header>
    <main
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
      "
    >
      <div
        style="
          width: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-bottom: 20px;
        "
      >
        <a style="width: 140px; margin-right: -10px; font-size: 20px"
          >选择电路：</a
        >
        <el-select
          v-model="results.value"
          placeholder="请选择电路"
          size="large"
          style="width: 60%"
        >
          <el-option
            v-for="item in result"
            :key="item"
            :label="item"
            :value="item"
            @click="getName(item)"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          size="large"
          style="background-color: #595959; margin-left: 2.5%"
          @click="reset"
          >重置</el-button
        >
      </div>
      <!-- 卡片-->
      <div style="width: 95%; display: flex; justify-content: center">
        <el-scrollbar
          max-height="650px"
          style="width: 100%; align-items: center; margin-top: -5px"
        >
          <el-card style="width: 98%; align-items: center; margin-top: -5px">
            <div
              style="
                display: flex;
                flex-direction: row;
                justify-content: space-between;
              "
            >
              <div style="width: 30%">
                <div style="width: 100%; max-height: 610px">
                  <div
                    style="
                      width: 100%;
                      height: 610px;
                      display: flex;
                      flex-direction: column;
                    "
                  >
                    <el-header
                      style="
                        font-size: 18px;
                        width: 98%;
                        margin-left: -12px;
                        justify-content: space-between;
                        align-items: center;
                      "
                    >
                      <div
                        style="
                          font-size: 18px;
                          width: 100%;
                          display: flex;
                          align-items: center;
                          justify-content: space-between;
                        "
                      >
                        <strong style="margin-left: -10px"
                          >仿真配置验证-发送验证：{{ circuitName }}
                        </strong>
                        <el-button
                          type="primary"
                          style="background-color: #000000"
                          @click="getSimulation"
                          >验证</el-button
                        >
                      </div>
                    </el-header>
                    <div>
                      <el-form v-model="response2">
                        <el-form-item>
                          <span class="span-style">
                            开始时间：{{ response2.begin_time }}</span
                          >
                        </el-form-item>
                        <el-form-item>
                          <span class="span-style"
                            >结束时间：{{ response2.end_time }}</span
                          >
                        </el-form-item>
                        <el-form-item>
                          <span class="span-style"
                            >验证耗时：{{ response2.cost_time }}</span
                          >
                        </el-form-item>
                        <el-form-item>
                          <span class="span-style"
                            >验证信息：{{ response2.content }}</span
                          >
                        </el-form-item>
                        <el-form-item v-if="isShowForm">
                          <span class="span-style">
                            当前电路正在计算中：{{ seconds }}...
                          </span>
                        </el-form-item>
                      </el-form>
                      <div
                        style="
                          width: 100%;
                          display: flex;
                          justify-content: center;
                          align-items: center;
                          flex-direction: column;
                        "
                      >
                        <a
                          style="
                            margin-bottom: -5px;
                            font-size: 20px;
                            margin-left: 0px;
                          "
                          >仿真验证-发送验证耗时</a
                        >
                        <div
                          ref="chartDom"
                          style="
                            width: 3800px;
                            height: 280px;
                            margin-bottom: -50px;
                          "
                        ></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- 中部-->
              <div style="width: 70%; display: flex; flex-direction: column">
                <div style="width: 98%; margin-top: 0px; height: 50%">
                  <ValidationVue
                    :message="circuitName"
                    v-if="ValidationVueLoaded"
                  />
                </div>
                <div style="display: flex; width: 100%">
                  <el-row style="width: 98%">
                    <div style="width: 70%">
                      <el-header
                        style="font-size: 18px; display: flex; width: 100%"
                      >
                        <div
                          style="
                            font-size: 18px;
                            width: 100%;
                            display: flex;
                            align-items: center;
                            justify-content: space-between;
                          "
                        >
                          <strong style="margin-left: -10px"
                            >仿真演算：{{ circuitName }}
                          </strong>
                        </div>
                        <el-button
                          type="primary"
                          style="background-color: #003f82"
                          @click="getAction"
                          >开始演算</el-button
                        >
                      </el-header>
                      <el-table
                        stripe
                        border
                        style="margin-top: 10px"
                        :data="response3"
                        max-height="250px"
                      >
                        <el-table-column
                          align="center"
                          label="开始时间"
                          prop="begin_time"
                          width="140"
                        ></el-table-column>
                        <el-table-column
                          align="center"
                          label="结束时间"
                          prop="end_time"
                          width="140"
                        ></el-table-column>
                        <el-table-column
                          align="center"
                          label="方法耗时"
                          prop="cost_time"
                          width="140"
                        ></el-table-column>
                        <el-table-column
                          align="center"
                          label="演算结果"
                          prop="content"
                        >
                          <template #default="scope">
                            <div
                              class="ellipsis"
                              @click="showDialog(scope.row.content)"
                            >
                              {{ scope.row.content }}
                            </div>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    <div
                      style="
                        width: 30%;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        flex-direction: column;
                      "
                    >
                      <a style="margin-bottom: -5px; font-size: 20px"
                        >仿真演算耗时</a
                      >
                      <div
                        ref="chartContainer"
                        style="width: 360px; height: 260px; margin-top: -50px"
                      ></div>
                    </div>
                  </el-row>
                </div>
              </div>
            </div>
          </el-card>
        </el-scrollbar>
      </div>
    </main>
    <el-dialog
      title="完整信息显示"
      v-model="dialogVisible"
      :before-close="handleClose"
      custom-class="custom-dialog"
    >
      <div v-html="dialogContent"></div>
    </el-dialog>
  </div>
</template>

<script setup name="仿真验证">
import {
  defineAsyncComponent,
  watch,
  reactive,
  ref,
  nextTick,
  onMounted,
  onUnmounted,
} from "vue";

import { ElMessage } from "element-plus";
import { getAlgorithm } from "@/server/algorithm";
import { circuitServer } from "@/server/iIndex";
import { getSimulationServer, getPymooEval } from "@/server/simulation.js";
import router from "@/router/index.js";
import * as echarts from "echarts";
import useUserInfoStore from "@/stores/userInfo.js";

const userInfoStore = useUserInfoStore();
const userInfo = userInfoStore.info;
const circuitName = ref("...");
const results = ref([]);
const result = ref([]);
const reqData = ref({
  circuit_diagram_name: "",
  user: userInfo,
});
let chartDom = ref(null);
let myChart = null;
let option = ref(null);

const dialogVisible = ref(false);
const dialogContent = ref("");

const showDialog = (content) => {
  dialogContent.value = content;
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
};

const reset = () => {
  router.go(0);
};
const getCircuit = async () => {
  try {
    const response = await circuitServer();
    results.value = response;
    result.value = results.value.name;
  } catch (error) {
    ElMessage.warning("获取电路失败");
    // console.error("出错了:", error);
  }
};
const isShowForm = ref(false);

const getName = (name) => {
  circuitName.value = name;
};

const response1 = ref([]);
const response2 = ref({
  begin_time: "...",
  content: "...",
  cost_time: "...",
  end_time: "...",
});
let formatDates = (time) => {
  if (time !== "-" && time) {
    time = Number(time);
    if (time < 1000) {
      return time.toFixed(2) + "ms";
    } else if (time < 60000) {
      return (time / 1000).toFixed(2) + "s";
    } else {
      const minutes = Math.floor(time / 60000);
      const seconds = ((time % 60000) / 1000).toFixed(2);
      return minutes + "min " + seconds + "s";
    }
  } else {
    return "计算中，请耐心等候...";
  }
};
const getSimulation = async () => {
  if (circuitName.value == "...") {
    ElMessage.info("请先选择电路");
    return;
  }
  try {
    const rep = await getAlgorithm(circuitName.value);
    if (!rep) {
      confirm("该电路未配置算法参数，请先配置算法参数");
      ElMessage.error("获取仿真验证信息失败");
      router.go(0);
      return;
    }
  } catch (e) {
    confirm("该电路未配置算法参数，请先配置算法参数");
    ElMessage.error("获取仿真验证信息失败");
    router.go(0);
    return;
  }

  try {
    reqData.value.circuit_diagram_name = circuitName.value;
    let response = await getSimulationServer(reqData.value);
    response1.value = response;

    let formatDate = (time) => {
      if (time !== "-" && time) {
        let date = new Date(Number(time));
        return date
          .toLocaleString("zh-CN", {
            hour12: false,
          })
          .replace(",", " ");
      } else {
        return "计算中，请耐心等候...";
      }
    };

    response2.value.begin_time = formatDate(response1.value.begin_time);
    response2.value.end_time = formatDate(response1.value.end_time);
    response2.value.cost_time = formatDates(response1.value.cost_time);

    response2.value.content =
      response1.value.content !== undefined && response1.value.content !== null
        ? response1.value.content === "计算中"
          ? "计算中，请耐心等候..."
          : response1.value.content
        : "...";
    if (response1.value.content === "计算中") {
      isShowForm.value = true;
    } else {
      isShowForm.value = false;
      stopTimer();
    }
    console.log(response2.value);
  } catch (e) {
    ElMessage.error("操作失败");
    isShowForm.value = false;
    stopTimer();
    console.error("e:", e);
  }
};

const timerId = ref(null);
const seconds = ref(0);

function startTimer() {
  console.log("调用了计时器1");
  timerId.value = setInterval(() => {
    seconds.value++;
    if (seconds.value % 30 === 0) {
      getSimulation();
    }
    updateChartData();
  }, 1000);
}

function stopTimer() {
  if (timerId.value) {
    clearInterval(timerId.value);
    timerId.value = null;
  }
}
watch(isShowForm, (newValue) => {
  if (newValue) {
    startTimer();
    // startTimer1();
  } else {
    stopTimer();
    // stopTimer1();
    seconds.value = 0; // 重置秒数
    totalSeconds2.value = 0; // 重置总秒数
    updateChartData();
  }
});
const getAction = () => {
  getSimulation2();
};
const ValidationVue = defineAsyncComponent(() =>
  import("@/components/simulation/validation.vue")
);
const ValidationVueLoaded = ref(false);
onMounted(async () => {
  // 确保组件加载完成后再设置标志位
  if (ValidationVue) {
    ValidationVueLoaded.value = true;
  }
  getCircuit();

  if (isShowForm.value) {
    startTimer();
  }
  nextTick(() => {
    if (chartDom.value) {
      myChart = echarts.init(chartDom.value);
      updateChartData();
    }
    if (chartContainer.value) {
      mySecondChart = echarts.init(chartContainer.value);
      mySecondChart.setOption(secondOption);
      updateChartData1();
    }
  });
});

onUnmounted(() => {
  stopTimer();
  stopTimer2();
  if (myChart) {
    myChart.dispose(); // 销毁第一个图表实例
  }
  if (mySecondChart) {
    mySecondChart.dispose(); // 销毁第二个图表实例
  }
});
const request = ref({
  user: userInfo,
  circuit_diagram_name: "",
});
const response3 = ref([]);
const getSimulation2 = async () => {
  if (circuitName.value == "...") {
    ElMessage.info("请先选择电路");
    return;
  }
  if (timerId2.value == null) {
    startTimer2();
  }
  let formatDates1 = (time) => {
    if (time !== "-" && time) {
      time = Number(time);
      if (time < 1000) {
        return time.toFixed(2) + "ms";
      } else if (time < 60000) {
        return (time / 1000).toFixed(2) + "s";
      } else {
        const minutes = Math.floor(time / 60000);
        const seconds = ((time % 60000) / 1000).toFixed(2);
        return minutes + "min " + seconds + "s";
      }
    } else {
      return "-";
    }
  };
  request.value.circuit_diagram_name = circuitName.value;
  console.log(userInfo);
  try {
    const response = await getPymooEval(request.value);
    const formattedResponse = {
      begin_time: formatDate1(response.begin_time),
      end_time: formatDate1(response.end_time),
      content:
        response.content !== undefined && response.content !== null
          ? response.content
          : "-",
      cost_time: formatDates1(response.cost_time),
    };
    response3.value = [formattedResponse]; // 将单个对象包装成数组
    if (response.content != "计算中") {
      stopTimer2();
    }
  } catch (e) {
    stopTimer2();
    ElMessage.error("操作失败");
    console.error("e:", e);
  }
};

const formatDate1 = (time) => {
  if (time !== "-" && time) {
    let date = new Date(Number(time));
    return date
      .toLocaleString("zh-CN", {
        hour12: false,
        year: "numeric",
        month: "2-digit",
        day: "2-digit",
        hour: "2-digit",
        minute: "2-digit",
      })
      .replace(/,/g, " ")
      .slice(5); // 只显示月时分
  } else {
    return "-";
  }
};

/* --------------------以下是Echarts代码-----------------------------*/
const timerId2 = ref(null);
const totalSeconds2 = ref(0);

function startTimer2() {
  console.log("调用了计时器2");
  timerId2.value = setInterval(() => {
    totalSeconds2.value++;
    if (totalSeconds2.value % 30 === 0) {
      getSimulation2();
    }
    updateChartData1();
  }, 1000);
}

function stopTimer2() {
  if (timerId2.value) {
    clearInterval(timerId2.value);
    timerId2.value = null;
  }
  totalSeconds2.value = 0;
  // mySecondChart.dispose();
}
// 更新图表数据的函数
async function updateChartData() {
  let dataSpeed = 0;
  let minutes = 0;
  let seconds1 = 0;

  // 如果 cost_time 存在，则使用 cost_time 的数据
  if (typeof response2.value.cost_time === "number") {
    dataSpeed = response2.value.cost_time;
    minutes = Math.floor(dataSpeed / 60);
    seconds1 = dataSpeed % 60;
  } else {
    // 否则，使用基于计时器的数据
    minutes = Math.floor(seconds.value / 60);
    seconds1 = seconds.value % 60;
  }

  // 确保分钟数不超过10，秒数不超过60
  minutes = minutes > 60 ? 60 : minutes;
  seconds1 = seconds1 > 60 ? 60 : seconds1;

  option.value = {
    series: [
      {
        type: "gauge",
        min: 0,
        max: 30,
        progress: {
          show: true,
          width: 18,
        },
        axisLine: {
          lineStyle: {
            width: 15,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          length: 8,
          lineStyle: {
            width: 2,
            color: "#999",
          },
        },
        axisLabel: {
          distance: 25,
          color: "#999",
          fontSize: 18,
        },
        anchor: {
          show: true,
          showAbove: true,
          size: 20,
          itemStyle: {
            borderWidth: 8,
          },
        },
        title: {
          show: false,
        },
        detail: {
          valueAnimation: true,
          fontSize: 28,
          offsetCenter: [0, "85%"],
          formatter: function () {
            return `${minutes} min ${seconds1} sec`;
          },
        },
        data: [
          {
            value: minutes, // 使用分钟数作为图表的数据值
          },
        ],
      },
    ],
  };
  myChart.setOption(option.value); // 应用新的配置选项
}
const chartContainer = ref(null);
let mySecondChart = null;
const secondOption = reactive({
  series: [
    {
      type: "gauge",
      startAngle: 180,
      endAngle: 0,
      center: ["50%", "75%"],
      radius: "90%",
      min: 0,
      max: 600,
      splitNumber: 8,
      axisLine: {
        lineStyle: {
          width: 6,
          color: [
            [0.25, "#58D9F9"],
            [0.75, "#7CFFB2"],
            [1, "#FDDD60"],
          ],
        },
      },
      pointer: {
        icon: "path://M12.8,0.7l12,40.1H0.7L12.8,0.7z",
        length: "12%",
        width: 20,
        offsetCenter: [0, "-60%"],
        itemStyle: {
          color: "auto",
        },
      },
      axisTick: {
        length: 12,
        lineStyle: {
          color: "auto",
          width: 2,
        },
      },
      splitLine: {
        length: 20,
        lineStyle: {
          color: "auto",
          width: 5,
        },
      },
      axisLabel: {
        color: "#464646",
        fontSize: 20,
        distance: -60,
        rotate: "tangential",
        formatter: function (value) {
          if (value === 0.875) {
            return "";
          } else if (value === 0.5) {
            return "";
          } else if (value === 0.125) {
            return "";
          }
          return "";
        },
      },
      title: {
        offsetCenter: [0, "-10%"],
        fontSize: 20,
      },
      detail: {
        fontSize: 25,
        offsetCenter: [0, "0%"],
        valueAnimation: true,
        formatter: function (value) {
          return Math.round(value) + "min";
        },
        color: "inherit",
      },
      data: [
        {
          value: 0, // 初始值设为0
          name: "",
        },
      ],
    },
  ],
});

// 更新图表数据的函数
async function updateChartData1() {
  let dataSpeed = 0;
  if (response3.value[0]) {
    if (
      typeof response3.value[0].cost_time === "number" &&
      response3.value[0].cost_time !== "-"
    ) {
      const begin = new Date(Number(response3.value[0].begin_time));
      const end = new Date(Number(response3.value[0].end_time));
      const diffInMs = Math.abs(end - begin);
      const diffInMinutes = Math.round(diffInMs / (1000 * 60));
      response3.value[0].cost_time = diffInMinutes;
      dataSpeed = diffInMinutes;
    } else {
      dataSpeed = totalSeconds2.value;
    }
  } else {
    dataSpeed = totalSeconds2.value;
  }

  const minutes = Math.floor(dataSpeed / 60);
  const seconds = dataSpeed % 60;

  const newOption = {
    ...secondOption,
    series: [
      {
        ...secondOption.series[0],
        data: [
          {
            value: minutes, // 使用分钟数作为图表的数据值
            name: "",
          },
        ],
        detail: {
          ...secondOption.series[0].detail,
          formatter: function (value) {
            return `${value}min${seconds < 10 ? "0" : ""}${seconds}sec`; // 格式化时间
          },
        },
      },
    ],
  };
  mySecondChart.setOption(newOption);
}
</script>

<style lang="scss" scoped>
.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer;
  display: block;
  /* 确保元素为块级元素 */
}

.custom-dialog .el-dialog {
  width: auto;
  /* 让宽度自适应内容 */
  max-width: 90%;
  /* 最大宽度限制 */
}

.span-style {
  margin-top: -5px;
  margin-bottom: -2px;
  font-size: 18px;
}

.table-header {
  background-color: black;
}

.inputStyle {
  width: 850px;
}

table {
  div {
    cursor: pointer;
  }
}

header {
  padding: 20px;
  background-color: #f8f9fa;
}

main {
  margin-top: 20px;
}

footer {
  text-align: center;
  margin-top: 20px;
}

.el-divider {
  margin-top: 10px;
  margin-bottom: -10px;
}
</style>
